package service

import (
	"errors"
	"gin-luban-server/global"
	"gin-luban-server/model"
	"gin-luban-server/model/request"
	"gorm.io/gorm"
)

//@author: heyibo
//@function: CreateConpany
//@description: 创建一个公司
//@param: auth model.SysConpany
//@return: err error, company model.SysConpany

func CreateConpany(company model.SysCompany) (err error) {
	if !errors.Is(global.GVA_DB.Where("company_code = ?", company.CompanyCode).First(&model.SysCompany{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在相同公司编码")
	}
	err = global.GVA_DB.Create(&company).Error
	return err
}

//@author: heyibo
//@function: UpdateConpany
//@description: 更新部门信息
//@param: company model.SysConpany
//@return:err error, station model.SysConpany

func UpdateConpany(company model.SysCompany) (err error) {
	var total int64
	var companyList []model.SysCompany
	err = global.GVA_DB.Where("company_code = ? AND id != ?",company.CompanyCode,company.ID).Find(&companyList).Count(&total).Error
	if total >= 1 {
		return errors.New("存在相同公司编码")
	}
	err = global.GVA_DB.Where("id= ?", company.ID).First(&model.SysCompany{}).Updates(&company).Error
	return err
}

//@author: heyibo
//@function: DeleteConpany
//@description: 删除部门信息
//@param: company *model.SysConpany
//@return: err error

func DeleteCompany(company *model.SysCompany) (err error) {
	db := global.GVA_DB.Preload("SysUsers").Preload("SysDepartments").First(company)
	if len(company.SysUsers) > 0 {
		return errors.New("有用户正在使用禁止删除")
	} else if len(company.SysDepartments) > 0 {
		return errors.New("有部门正在使用禁止删除")
	}
	err = db.Delete(&company).Error
	return err
}

//@author: heyibo
//@function: GetConpanyInfoList
//@description: 分页获取数据
//@param: info request.PageInfo
//@return: err error, list interface{}, total int64

func GetConpanyInfoList(info request.SysCompanySearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&model.SysCompany{})
	var company []model.SysCompany

	if info.CompanyName != "" {
		db = db.Where("`company_name` LIKE ?", "%"+info.CompanyName+"%")
	}
	if info.CompanyCode != "" {
		db = db.Where("`company_code` = ?", info.CompanyCode)
	}
	if info.Status != nil {
		db = db.Where("`status` = ?", info.Status)
	}
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&company).Error
	return err, company, total
}

//@author: heyibo
//@function: FindCompanyrById
//@description: 通过id获取公司信息
//@param: id int
//@return: err error, user *model.SysCompany

func FindCompanyById(id float64) (err error, company model.SysCompany) {
	err = global.GVA_DB.Where("`id` =  ? ", id).First(&company).Error
	return
}

//@author: heyibo
//@function: FindCompanyrAllList
//@description: 通过id获取公司信息
//@param: id int
//@return: err error, user *model.SysCompany

func FindCompanyAllList() (err error, company []model.SysCompany) {
	err = global.GVA_DB.Model(&model.SysCompany{}).Find(&company).Error
	return
}
